<?php


namespace app\app\controller;


use app\constant\ActivesConst;
use app\constant\OrderConst;
use app\model\AdminActives;
use app\model\AdminKanjiaHelp;
use app\model\AdminKanjiaOrder;
use app\model\AdminOrder;
use app\model\AdminStores;
use app\model\AdminStoreTag;
use app\model\AppWxUser;
use app\util\ReturnCode;
use Exception;
use think\Db;
use think\db\Where;
use think\exception\DbException;

class Goods extends Base
{

    public function getDetail()
    {
        $id = $this->request->param('id');
        if (!isset($id)) {
            return $this->buildFailed(ReturnCode::INVALID, '无效的id');
        } else {
            $model = AdminActives::get($id,null,true);
            if ($model) {
                $sku = $model->sku;
                $data = $model->getData();
                try {
                    $storeData = AdminStores::get($data['sid'],null,true)->getData();
//                    $storeData = (new AdminStores())->where('id', $data['sid'])->cache('admin_stores')->field('name,phone,address,ln,la,tag,store_img')->find();
                    if (isset($storeData['tag'])&&$storeData['tag']!=-1) {
                        $tagImg = AdminStoreTag::get($storeData['tag'],null,true)->getData();
                        $storeData['tag_img'] = $tagImg['icon'];
                    }
                    $data['store_data'] = $storeData;
                    $uids = (new AdminOrder())->group("uid")
                        ->where(['goods_id'=>$id,'pay_status'=>OrderConst::PAY_STATUS_PAID_ONLINE])
                        ->cache('latest_bougth_user_' .$id ,3*60 )
                        ->field('uid')
                        ->order('create_time','desc')
                        ->limit(10)
                        ->select()->toArray();
                    $uidArr = [];
                    foreach ($uids as $uid){
                        $uidArr[] = $uid['uid'];
                    }
                    $wxUserData= (new AppWxUser())
                        ->cache(null,2*60*60)
                        ->whereIn('id',$uidArr)
                        ->field('nickname,head_img')
                        ->select();
                    $data['latest_bougth_user'] = $wxUserData;
                } catch (Exception $e) {
                }
                $views = cache(ActivesConst::VIEWS_TAG . $id);
                $data['views'] = intval($views) + $data['views'] + $data['init_views'];
                $data['sales'] = $data['sales'] + $data['init_sales'];
                $data['sku'] = $sku;
                //如果是砍价活动，则获取相应的信息
                if($data['type']===ActivesConst::ACTIVE_TYPE_KJ){
                    //先判断是助力还是参加
                    $kanjiaId = $this->request->param('kanjia_id');
                    //如果有，要判断下是自己的链接还是别人的链接
                    if(isset($kanjiaId)){
                        $kanjiaModel = AdminKanjiaOrder::get($kanjiaId,null,true);
                        if($kanjiaModel){
                            return $this->buildFailed(ReturnCode::INVALID, '获取失败');
                        }
                        //如果相同，说明是自己的链接
                        $data['kanjia_data']=$kanjiaModel->getData();
                    }else{
                        if($this->userInfo!=null){
                            //先判断当前用户是否参加
                            $kanjiaModel = AdminKanjiaOrder::get(['tid'=>$data['tid'],'goods_id'=>$data['id'],'uid'=>$this->userInfo['uid']]);
                            if($kanjiaModel){
                                $data['kanjia_data']=$kanjiaModel->getData();
                            }else{
                                $data['kanjia_data'] = null;
                            }
                        }
                    }
                    if($data['kanjia_data']!=null){
                        //获取当前订单用户信息
                        $wxUser = AppWxUser::get($data['kanjia_data']['uid'],null,true);
                        $data['kanjia_data']['user_info'] = $wxUser->getData();
                        //判断是否帮砍过价了
                        $helpModel = AdminKanjiaHelp::get(['tid'=>$data['tid'],'kanjia_order_id'=>$data['kanjia_data']['id'],'uid'=>$this->userInfo['uid']]);
                        if($helpModel){
                            $data['kanjia_data']['is_help'] = true;
                        }else{
                            $data['kanjia_data']['is_help'] = false;
                        }
                    }
                }
                return $this->buildSuccess($data);
            }
        }
        return $this->buildFailed(ReturnCode::INVALID, '获取失败');
    }
    public function getSampleDetail()
    {
        $id = $this->request->param('id');
        if (!isset($id)) {
            return $this->buildFailed(ReturnCode::INVALID, '无效的id');
        } else {
            $model = AdminActives::get($id,null,true);
            if ($model) {
                $sku = $model->sku;
                $data = $model->getData();
                $data['sku'] = $sku;
                return $this->buildSuccess($data);
            }
        }
        return $this->buildFailed(ReturnCode::INVALID, '获取失败');
    }
    public function getList(){
        $categoryId = $this->request->param('category_id');
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $keyword= $this->request->get('keyword', null);
        $where = new Where;
        $where['del'] =0;
        $where['status'] =['in',[ActivesConst::STATUS_WAIT,ActivesConst::STATUS_NORMAL,ActivesConst::STATUS_STOP,ActivesConst::STATUS_SOLD_OUT]];
        $where = $this->addTid($where);

        if(isset($categoryId)){
            $where['category_id'] = $categoryId;
        }
        if(isset($keyword)){
            $where['title']= ['like','%'.$keyword.'%'];
        }
        try {
            $subsql = Db::table('admin_active_sku sku')->alias('sku')
                ->field('min(lowest_price) as price,sum(sales + init_sales) as sales,vip_discount,aid')
                ->group('aid')
                ->buildSql();
            $listObj = Db::table('admin_actives')->alias('actives')
                ->where($where)
                ->field('actives.banners as banner,actives.create_time as create_time,actives.id as goods_id,actives.banners as banner,actives.title as title,actives.status as status')
                ->join([$subsql => 'sku'], 'actives.id = sku.aid')
                ->field('sku.price as price,sku.sales as sales,vip_discount')
                ->order('create_time DESC')
                ->order('status ASC')
                ->paginate($limit, false, ['page' => $start])
                ->toArray();
            return $this->buildSuccess([
                'list' => $listObj['data'],
                'count' => $listObj['total']
            ]);
        } catch (DbException $e) {
        }
        return $this->buildFailed(ReturnCode::FAILED, '获取失败');
    }
}